#!/usr/bin/env python

import socket

server_addr = ("127.0.0.1", 8080)
recv_len = 1024
calc_count = 3
n = int(1e5)
calc_list = [
    ("127.0.0.1", 8081),
    ("127.0.0.1", 8082),
    ("127.0.0.1", 8083)
]

#Bind socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(server_addr)
print("Start server")

while True:
#Recv argc from Tasker
    a, tasker_addr = sock.recvfrom(recv_len)
    b, tasker_addr = sock.recvfrom(recv_len)
    a, b = float(a.decode()), float(b.decode())
    if a > b:
        a, b = b, a
    print(a, " | ", b)

#Send arg part to Calculators
    part_len = (b - a) / calc_count
    b = a
    for i in calc_list:
        b += part_len
        sock.sendto(str(a).encode(), i)
        sock.sendto(str(b).encode(), i)
        a += part_len
#Recv results from Calculators
    result = 0
    for i in calc_list:
        sock.sendto(str("READY").encode(), i)
        res_part, addr = sock.recvfrom(recv_len)    
        result += float(res_part.decode())
#Send func value to Tasker
    sock.sendto(str(result).encode(), tasker_addr)
